<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        canvas {
            border: 1px solid black;
        }
    </style>
</head>

<body>
    <button id="btn1">180°旋转图片</button>
    <button id="btn2">镜像翻转图片</button>
    <br>
    <img src="face.png" alt="">
    <script>
        window.onload = function () {
            let img = document.querySelector('img')
            let img_width = img.width
            let img_height = img.height
            let btn1 = document.querySelector('#btn1')
            let btn2 = document.querySelector('#btn2')
            btn1.onclick = function () {
                let canvas = document.createElement('canvas')
                document.body.appendChild(canvas)
                canvas.width = img_width // 根据图像大小来动态生成canvas
                canvas.height = img_height
                if (canvas.getContext) {
                    let context = canvas.getContext('2d');
                    // 如果不移动，绘制图片的效果如图1
                    // 移动原点到canvas的中心点：成像效果如图2
                    context.translate(img_width / 2, img_height / 2) 
                    context.rotate(Math.PI) // 绕原点顺时针旋转Pi个弧度,成像效果如图3
                    // 在画布的(-img_width / 2, -img_height / 2)处开始，绘制图像
                    context.drawImage(img, -img_width / 2, -img_height / 2) 
                }
            }
            btn2.onclick = function(){
                let canvas = document.createElement('canvas')
                document.body.appendChild(canvas)
                canvas.width = img_width
                canvas.height = img_height
                if (canvas.getContext) {
                    // scale(1, 1) ：默认
                    // scale(-1,1)：水平翻转
                    // scale(1,-1)：垂直翻转
                    // scale(-1,-1)：水平垂直翻转
                    let context = canvas.getContext('2d');
                    context.translate(img_width / 2, img_height / 2)
                    context.scale(1,-1) //：垂直翻转
                    context.drawImage(img, -img_width / 2, -img_height / 2)
                }
            }
        }
    </script>
</body>

</html>
